<template>
  <div :class="{'device-bg': devicesList.length !== 0}" class="cigar--device-control">
    <div v-show="loadData" :style="{'display': 'flex', 'flex-direction': 'column', 'height': '100%'}">
      <!-- 设备在线 -->
      <div v-if="devicesList.length !== 0" class="changeScreen" :class="{onlineHight: !currentDeviceOffline}">
        <div class="header" @click="showDeviceList" v-clickoutside="onClose" id="header" ref="headerHeight">
          <div class="current-device--name">当前设备 : {{ uiCurrentDevice.name }}</div>
          <div class="down__arrow"></div>
          <div class="deviceList-warp__icon-angle" v-show="deviceListWarp"></div>
          <div class="deviceList-warp" v-show="deviceListWarp">
            <div class="deviceList">
              <div @click="selectDevice(device)" v-for="(device, index) in uiDeviceList" class="inner-wrap" :key="index">
                <div class="deviceList--per">
                  {{ device.name }}
                  <div :class="device.name === uiCurrentDevice.name ? 'selectImg' : ''"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="detail" v-show="!currentDeviceOffline">
          <div class="top-floor__info clearfix" v-show="!isTopFloor" @click="toggleFloor">
            <div class="fl temp">
              <span class="floor">上层</span>
              <div>
                <span>当前温度</span>
                <span>{{ UpfilterTemp }}</span>
                <span>{{ tempuratureType.value === 0 ? '℃' : 'F' }}</span>
              </div>
            </div>
            <div class="fr humidity">
              <div class="humidity--value">
                <span>当前湿度</span>
                <span>{{ UpfilterHum }}</span>
                <span>%</span>
              </div>
              <div class="down__arrow"></div>
            </div>
          </div>
          <div class="top-floor__detail" v-show="isTopFloor">
            <div class="top-tip clearfix">
              <span class="fl">上层</span>
              <span class="fr" @click.stop="isEditingStatus(0)">{{ isUpSetting ? '完成' : '设置' }}</span>
            </div>
            <div class="top-detail clearfix">
              <div class="left left--position temp">
                <div @click.prevent="changeTempOrHum(0)" class="circle">
                  <div class="current-temp__wrap">
                    <div>
                      <span class="current-temp--value">{{ isUpSetting ? tempurature[1].value : UpfilterTemp }}</span>
                      <span class="current-temp--unit">{{tempuratureType.value === 0 ? '℃' : 'F' }}</span>
                    </div>
                    <span class="current-temp--title">{{ isUpSetting ? '设定温度' : '当前温度'}}</span>
                  </div>
                  <div class="range__temp">
                    <span class="min-temp fl">{{ tempurature[3].value }}</span>
                    <span class="max-temp fr">{{ tempurature[2].value }}</span>
                  </div>
                  <div class="edit__icon" v-show="isUpSetting"></div>
                    <tempCircle :percent="UpTempPercent" :width="width" :height="height"></tempCircle>
                  </div>
              </div>
              <div class="right right--position humidity">
                <div @click="changeTempOrHum(1)" class="circle">
                  <div class="current-humidity__wrap">
                    <div>
                      <span class="current-humidity--value">{{ isUpSetting ? humidity[1].value : UpfilterHum }}</span>
                      <span class="current-humidity--unit">%</span>
                    </div>
                    <span class="current-humidity--title">{{isUpSetting ? '设定湿度' : '当前湿度'}}</span>
                  </div>
                  <div class="range__humidity">
                    <span class="min-hum fl">{{ humidity[3].value }}</span>
                    <span class="max-hum fr">{{ humidity[2].value }}</span>
                  </div>
                  <div class="edit__icon" v-show="isUpSetting"></div>
                    <tempCircle :percent="UpHumPercent" :width="width" :height="height"></tempCircle>
                  </div>
              </div>
            </div>
          </div>
          <div class="bottom-floor__info clearfix" v-show="isTopFloor" @click="toggleFloor">
            <div class="fl temp">
              <span class="floor">下层</span>
              <div>
                <div>
                  <span>当前温度</span><span>{{ DownfilterTemp }}</span><span>{{ tempuratureType.value === 0 ? '℃' : 'F' }}</span>
                </div>
              </div>
            </div>
            <div class="fr humidity">
              <div class="humidity--value">
                <span>当前湿度</span><span>{{ DownfilterHum }}</span><span>%</span>
              </div>
              <div class="down__arrow"></div>
            </div>
          </div>
          <div class="bottom-floor__detail" v-show="!isTopFloor">
            <div class="top-tip clearfix">
              <span class="fl">下层</span>
              <span class="fr" @click.stop="isEditingStatus(1)">{{ isDownSetting ? '完成' : '设置'}}</span>
            </div>
            <div class="top-detail clearfix">
              <div class="left left--position temp">
                <div @click="changeTempOrHum(2)" class="circle">
                  <div class="current-temp__wrap">
                    <div>
                      <span class="current-temp--value">{{ isDownSetting ? tempurature[5].value : DownfilterTemp }}</span>
                      <span class="current-temp--unit">{{tempuratureType.value === 0 ? '℃' : 'F' }}</span>
                    </div>
                    <span class="current-temp--title">{{ isDownSetting ? '设定温度' : '当前温度'}}</span>
                  </div>
                  <div class="range__temp">
                    <span class="min-temp fl">{{ tempurature[7].value }}</span>
                    <span class="max-temp fr">{{ tempurature[6].value }}</span>
                  </div>
                  <div class="edit__icon" v-show="isDownSetting"></div>
                    <tempCircle :percent="DownTempPercent" :width="width" :height="height"></tempCircle>
                  </div>
              </div>
              <div class="right right--position humidity">
                <div @click="changeTempOrHum(3)" class="circle">
                  <div class="current-humidity__wrap">
                    <div>
                      <span class="current-humidity--value">{{ isDownSetting ? humidity[5].value : DownfilterHum }}</span>
                      <span class="current-humidity--unit">%</span>
                    </div>
                    <span class="current-humidity--title">{{ isDownSetting ? '设定湿度' : '当前湿度'}}</span>
                  </div>
                  <div class="range__humidity">
                    <span class="min-hum fl">{{ humidity[7].value }}</span>
                    <span class="max-hum fr">{{ humidity[6].value }}</span>
                  </div>
                  <div class="edit__icon" v-show="isDownSetting">
                  </div>
                  <tempCircle :percent="DownHumPercent" :width="width" :height="height"></tempCircle>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="switch" v-show="!currentDeviceOffline">
          <group style="flex: 1;display: flex;flex-direction: column;">
            <flexbox class="vux-1px-b" v-for="(mode, index) in type" :key="index" style="flex:1">
              <flexbox-item :span="1"> 
                <div class="secondary__img--size" :class="mode.title"></div>
              </flexbox-item>
              <!-- mark -->
              <flexbox-item class="normalSwitch">
                <x-switch 
                  :title="mode.name"
                  :value="mode.title === 'Lamplight_Switch'? mode.value - 0 === 2 : mode.value - 0 === 1"
                  :inline-desc="barRemainingTime(mode)"
                  @on-change="val => currentOnoff(val, mode, index === 3)">
                </x-switch>
              </flexbox-item>
              <flexbox-item v-show=" mode.title === 'Lamplight_Switch' "  class="Lamplight" >
                <x-switch 
                  :title="mode.name"
                  :value="mode.value - 0 === 1"
                  @on-change="val => currentOnoff(val, mode, index === 3, true)">
                </x-switch>
              </flexbox-item>
              <div v-show=" mode.title === 'Lamplight_Switch' ">
                <div class="normal normal-light-status-right" >一般</div>
                <div class="light always-light-status-right" >常亮</div>
              </div>
            </flexbox>
          </group>
          <group class="temp-humidity__curve orientToggle">
            <cell  @click.native="goUrlCurve()" title="温湿度曲线" is-link>
              <img slot="icon" class="temp-humidity__icon icon" src="../../assets/cigrImage/temp-humidity__curve.png">
            </cell>
          </group>
        </div>
      </div>
      <!-- 无设备，添加设备 -->
      <div v-else class="null-data">
        <div class="bg-img-setting">
          <img src="../../assets/cigrImage/offline_icon.png" alt="" class="bg-img-detail">
        </div>
        <div class="mb10 null-device">
          <p>暂无关联设备</p>
        </div> 
        <div class="addDevice">
          <x-button @click.native = "addDevice" class="custom-primary-brown vux-1px-radius add-font-color" >添加设备</x-button>
        </div>
      </div>
      <!-- 设备不在线 -->
      <div class="currentDeviceOffline" v-show="currentDeviceOffline"> 
         <!-- <div>
           当前设备不在线
         </div> -->
         <div class="bg-img-setting">
          <img src="../../assets/cigrImage/offline_icon.png" alt="" class="bg-img-detail">
        </div>
        <div class="mb10 null-device">
          <p>当前设备不在线</p>
        </div> 
        <div class="addDevice">
          <x-button @click.native="refresh" class="custom-primary-brown vux-1px-radius add-font-color">刷新</x-button>
        </div>
      </div> 

      <!-- 固定底部的弹窗 -->
      <div class="container"></div>

    </div>
    <div v-transfer-dom class="toast-modify">
      <loading v-model="loading" :text="text"></loading>
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import { Flexbox, FlexboxItem, XSwitch, Group, Cell, Selector, XButton, Loading, TransferDomDirective as TransferDom } from 'vux'
import wx from 'weixin-js-sdk'
import clickoutside from '@/directives/clickoutside'
import { mapGetters } from 'vuex'
import tempCircle from './circle'
import { CIGARTYPE } from './CIGARTYPE'
import IosSelect from 'iosselect'
export default {
  name: 'cigarDeviceController',
  components: {
    Flexbox,
    FlexboxItem,
    XSwitch,
    Group,
    Cell,
    Selector,
    tempCircle,
    Loading,
    XButton
  },
  directives: {
    clickoutside,
    TransferDom
  },
  data () {
    return {
      ws: {},
      isDownShowSelect: false,
      isUpSetting: false,
      isDownSetting: false,
      isCommit: 0,
      isUpCommit: 0,
      isDownCommit: 0,
      changeNewData: {
        UpTempChange: false,
        UpHumChange: false,
        DownTempChange: false,
        DownHumChange: false
      },
      text: '正在刷新请稍后',
      isTopFloor: true,
      percent: 50,
      width: 120,
      height: 120,
      isEdit: false,
      loadData: false,
      loading: true,
      deviceListWarp: false,
      currentDevice: null,
      currentDeviceOffline: false,
      // devicesList是用于连接socket的列表和getNameDevicesList字段不同
      devicesList: [],
      // 选中的温湿度
      selectUpFloorTemp: 0,
      selectUpFloorHum: 0,
      selectDownFloorTemp: 0,
      selectDownFloorHum: 0,
      isEditing: '',
      type: [
        {
          name: '裸养模式',
          title: 'Naked_Support_Mode',
          key: CIGARTYPE.Naked_Support_Mode,
          value: 0
        }, {
          name: '醒茄模式',
          title: 'Wake_Cigar_Mode',
          key: CIGARTYPE.Wake_Cigar_Mode,
          value: 0
        }, {
          name: '净味除菌',
          title: 'Net_Flavor_Degerming',
          key: CIGARTYPE.Net_Flavor_Degerming,
          value: 0
        }, {
          name: '灯光开关',
          title: 'Lamplight_Switch',
          key: CIGARTYPE.Lamplight_Switch,
          value: 0
        }
      ],
      countDown: [
        {
          name: '醒茄倒计时',
          title: 'Wake_Cigar_Countdown',
          key: CIGARTYPE.Wake_Cigar_Countdown,
          value: 30
        },
        {
          name: '净味除菌运行时间',
          title: 'Net_Flavor_Degerming_time',
          key: CIGARTYPE.Net_Flavor_Degerming_time,
          value: 20
        },
        {
          name: '灯光倒计时',
          title: 'Lamplight_Count',
          key: CIGARTYPE.Lamplight_Count,
          value: 20
        }
      ],
      tempuratureType: {
        name: '温度单位',
        title: 'Tempurature_Type',
        key: CIGARTYPE.Tempurature_Type,
        value: 2
      },
      tempurature: [
        {
          name: '上区显示温度',
          title: 'Up_Display_Tempurature',
          key: CIGARTYPE.Up_Display_Tempurature,
          value: 3
        },
        {
          name: '上区设置温度',
          title: 'Up_Set_Tempurature',
          key: CIGARTYPE.Up_Set_Tempurature,
          value: 4
        },
        {
          name: '上区温度最大',
          title: 'Up_Tempurature_Max',
          key: CIGARTYPE.Up_Tempurature_Max,
          value: 11
        },
        {
          name: '上区温度最小',
          title: 'Up_Tempurature_Min',
          key: CIGARTYPE.Up_Tempurature_Min,
          value: 12
        },
        {
          name: '下区显示温度',
          title: 'Down_Set_Tempurature',
          key: CIGARTYPE.Down_Display_Tempurature,
          value: 7
        },
        {
          name: '下区设置温度',
          title: 'Down_Set_Tempurature',
          key: CIGARTYPE.Down_Set_Tempurature,
          value: 8
        },
        {
          name: '下区温度最大',
          title: 'Down_Tempurature_Max',
          key: CIGARTYPE.Down_Tempurature_Max,
          value: 15
        },
        {
          name: '下区温度最小',
          title: 'Down_Tempurature_Min',
          key: CIGARTYPE.Down_Tempurature_Min,
          value: 16
        }
      ],
      humidity: [
        {
          name: '上区显示湿度',
          title: 'Up_Display_Humidity',
          key: CIGARTYPE.Up_Display_Humidity,
          value: 3
        },
        {
          name: '上区设置湿度',
          title: 'Up_Set_Humidity',
          key: CIGARTYPE.Up_Set_Humidity,
          value: 4
        },
        {
          name: '上区湿度最大',
          title: 'Up_Humidity_Max',
          key: CIGARTYPE.Up_Humidity_Max,
          value: 13
        },
        {
          name: '上区湿度最小',
          title: 'Up_Humidity_Min',
          key: CIGARTYPE.Up_Humidity_Min,
          value: 14
        },
        {
          name: '下区显示湿度',
          title: 'Down_Set_Humidity',
          key: CIGARTYPE.Down_Display_Humidity,
          value: 7
        },
        {
          name: '下区设置湿度',
          title: 'Down_Set_Humidity',
          key: CIGARTYPE.Down_Set_Humidity,
          value: 8
        },
        {
          name: '下区湿度最大',
          title: 'Down_Humidity_Max',
          key: CIGARTYPE.Down_Humidity_Max,
          value: 17
        },
        {
          name: '下区湿度最小',
          title: 'Down_Humidity_Min',
          key: CIGARTYPE.Down_Humidity_Min,
          value: 18
        }
      ],
      // isToggle: false,
      orientation: 'portrait'
    }
  },
  computed: {
    // 设备列表
    ...mapGetters({
      socketList: 'control/socketList',
      currentSocket: 'control/currentSocket',
      getNameDevicesList: 'control/cigarDeviceList',
      uiDevice: ['control/uiDevice']
    }),

    UpfilterTemp () {
      return Math.round(parseFloat(this.tempurature[0].value))
    },
    UpfilterHum () {
      return Math.round(parseFloat(this.humidity[0].value))
    },
    DownfilterTemp () {
      return Math.round(parseFloat(this.tempurature[4].value))
    },
    DownfilterHum () {
      return Math.round(parseFloat(this.humidity[4].value))
    },

    // 环形进度条百分比
    UpTempPercent () {
      // 1:当前温度减去最小温度 除以 最大和最小温度差值（百分比）
      // 2:编辑状态下(即右上角显示‘完成’) 不显示进度条
      // 当前温度大于最大温度 直接显示100%
      // 当前温度小于最小温度 直接显示0%
      let [{value: current}, , {value: max}, {value: min}] = this.tempurature
      return this.processComputed(current, min, max)
    },
    UpHumPercent () {
      let [{value: current}, , {value: max}, {value: min}] = this.humidity
      return this.processComputed(current, min, max)
    },
    DownTempPercent () {
      let [, , , , {value: current}, , {value: max}, {value: min}] = this.tempurature
      return this.processComputed(current, min, max, 'Down')
    },
    DownHumPercent () {
      let [, , , , {value: current}, , {value: max}, {value: min}] = this.humidity
      return this.processComputed(current, min, max, 'Down')
    },

    // 根据温度最大值和最小值调整可选择的范围
    upFloorTempRange () {
      return this.options({max: CIGARTYPE.Up_Tempurature_Max, min: CIGARTYPE.Up_Tempurature_Min})
    },
    upFloorHumRange () {
      return this.options({max: CIGARTYPE.Up_Humidity_Max, min: CIGARTYPE.Up_Humidity_Min})
    },
    downFloorTempRange () {
      return this.options({max: CIGARTYPE.Down_Tempurature_Max, min: CIGARTYPE.Down_Tempurature_Min})
    },
    downFloorHumRange () {
      return this.options({max: CIGARTYPE.Down_Humidity_Max, min: CIGARTYPE.Down_Humidity_Min})
    },

    // 设备列表数据格式不一致，进行计算
    uiDeviceList () {
      let uiDeviceList = []
      if (this.getNameDevicesList && this.getNameDevicesList.length !== 0) {
        this.getNameDevicesList.forEach((item) => {
          let name = item.device_name ? item.device_name : item.device_mac
          uiDeviceList.push({
            name: name,
            id: item.device_id
          })
        })
        this.$store.dispatch('control/uiDeviceList', uiDeviceList)
        return uiDeviceList
      }
    },
    uiCurrentDevice () {
      return this.uiDevice || (this.uiDeviceList && this.uiDeviceList[0])
    },
    allType () {
      return _.concat(this.tempurature, this.type, this.countDown, this.humidity, this.tempuratureType)
    }
  },
  mounted () {
    window.localStorage.removeItem('currentDeviceId')
    this.$Title.set('美晶智能雪茄柜')
    this.initalize()
  },
  watch: {
    socketList (newTemp) {
      if (newTemp.length) {
        this.initalize()
      }
    },
    selectUpFloorTemp (newTemp, older) {
      if (newTemp === older) return
      this.changeNewData.UpTempChange = true
      this.tempurature[1].value = newTemp
    },
    selectUpFloorHum (newHum, older) {
      if (newHum === older) return
      this.changeNewData.UpHumChange = true
      this.humidity[1].value = newHum
    },
    selectDownFloorTemp (newTemp, older) {
      if (newTemp === older) return
      this.changeNewData.DownTempChange = true
      this.tempurature[5].value = newTemp
    },
    selectDownFloorHum (newHum, older) {
      if (newHum === older) return
      this.changeNewData.DownHumChange = true
      this.humidity[5].value = newHum
    }
  },
  methods: {
    async initalize () {
      if ([-90, 0, 90, 180].indexOf(window.orientation) !== -1) {
        this.fetchWidth()
        this.fetchHeight()
      }
      this.resize()

      // 设备列表包含雪茄柜和红酒柜需要过滤
      // 连接实例为空的时候直接return
      if (!this.socketList.length) {
        this.loadData = true
        this.loading = false
        return
      }
      this.devicesList = this.socketList
      // 设备列表为空
      if (this.getNameDevicesList.length === 0) {
        this.loadData = true
        this.loading = false
        return
      }
      // 获取所有连接实例，包含红酒柜和雪茄柜，首次进入默认选择该产品的第一个产品，切换产品列表的时候发送当前连接实例
      let fetchCurrentSocket = this.$store.getters['control/currentSocket']
      if (fetchCurrentSocket) {
        this.currentDevice = fetchCurrentSocket
      } else {
        this.currentDevice = this.devicesList.filter((value) => {
          return value.id === this.getNameDevicesList[0].device_id
        })[0]
      }
      window.localStorage.setItem('currentDeviceId', this.currentDevice.id)
      this.linkSocket(this.currentDevice)
    },
    // 连接socket
    linkSocket (currentDevice) {
      currentDevice.on('data', (data) => {
      // 后台改变的和当前设备不一致的时候不更新数据(后台多台设备，改变的不一定是当前显示的设备)
        if (this.currentDevice !== currentDevice) return
        if (data.type === 'datapoint') {
          // 数据端点
          this.updateData(data.data)
        }
      })
      // 获取后台的数据端点
      currentDevice.emit('probe', (devices) => {
        if (devices.status === 0) {
          this.loadData = true
          this.loading = false
          this.currentDeviceOffline = false
          // 转化allType数据格式进行遍历
          devices.data.forEach(devices => {
            this.allType.forEach(item => {
              if (item.key === devices.index) {
                item.value = devices.value
              }
            })
          })
          this.storageTempAndHum()
        } else {
          this.loadData = true
          this.loading = false
          this.currentDeviceOffline = true
        }
      })
    },
    // 本地更改数据反映到后台
    changeData (changeData) {
      let _self = this
      let data = [{
        index: changeData.key,
        value: changeData.value
      }]
      this.currentDevice.emit('senddata', {
        type: 'datapoint',
        data: data
      }, function (res) {
        if (res.status === 0) {
          _self.successTip()
          _self.updateData(data)
        }
      })
    },
    // 后台更新数据映射到本地
    updateData (newDatas) {
      _.forEach(newDatas, (newData) => {
        _.forEach(this.allType, (oldData) => {
          if (oldData.key === newData.index) {
            oldData.value = newData.value
          }
        })
      })
      this.storageTempAndHum()
    },
    // 设备列表
    showDeviceList () {
      this.deviceListWarp = !this.deviceListWarp
    },
    // 为下拉框初始值赋值
    storageTempAndHum () {
      this.selectUpFloorTemp = this.tempurature[1].value
      this.selectUpFloorHum = this.humidity[1].value
      this.selectDownFloorTemp = this.tempurature[6].value
      this.selectDownFloorHum = this.humidity[6].value
    },
    // 选择设备
    selectDevice (selectedDevice) {
      // 外层循环通过名字查找对应的mac 内层转换成连接socket的数据格式
      _.filter(this.getNameDevicesList, (device) => {
        if (device.device_name === selectedDevice.name || device.device_mac === selectedDevice.name) {
          _.filter(this.devicesList, (item) => {
            if (item.mac === device.device_mac) {
              this.currentDevice = item
              this.$store.dispatch('control/currentSocket', item)
              this.linkSocket(this.currentDevice)
            }
          })
        }
      })
      this.$store.dispatch('control/uiDevice', selectedDevice)
      // 为曲线图刷新页面获取正确的当前设备（刷新会重新跑）
      window.localStorage.setItem('currentDeviceId', selectedDevice.id)
    },
    onClose () {
      this.deviceListWarp = false
    },

    // 切换floor
    toggleFloor () {
      this.isTopFloor = !this.isTopFloor
    },
    // 温湿度范围
    options ({max = 100, min = 0}) {
      let result = []
      let maxTemp = _.find(this.allType, (item) => {
        return item.key === max
      })
      let minTemp = _.find(this.allType, (item) => {
        return item.key === min
      })
      if (minTemp && maxTemp) {
        for (var i = minTemp.value; i <= maxTemp.value; i++) {
          result.push({
            id: i,
            value: i
          })
        }
        return result
      }
    },
    // 选择温湿度
    changeTempOrHum (target) {
      // 非编辑状态下不允许选择温湿度 0 1对应上层  2 3 对应下层
      if ((target === 0 || target === 1) && !this.isUpSetting) return
      if ((target === 2 || target === 3) && !this.isDownSetting) return
      let changeTargetArray = ([
        'selectUpFloorTemp',
        'selectUpFloorHum',
        'selectDownFloorTemp',
        'selectDownFloorHum'])[target]
      let val = this[changeTargetArray]
      // 实例化组件
      let range = ([
        'upFloorTempRange',
        'upFloorHumRange',
        'downFloorTempRange',
        'downFloorHumRange'])[target]
      let data = this[range]
      let iosExample = new IosSelect(1, [data],             // 第一个参数为级联层级，演示为1
        {
          container: '.container',             // 容器class
          title: target === 0 || target === 2 ? '设置温度' : '设置湿度',                    // 标题
          itemHeight: 50,                      // 每个元素的高度
          itemShowCount: 3,                    // 每一列显示元素个数，超出将隐藏
          oneLevelId: val,                     // 第一级默认值
          callback: (selectOneObj) => { // 用户确认选择后的回调函数
            this[changeTargetArray] = selectOneObj.id
          }
        })
      console.log(iosExample)
    },
    // 温湿度编辑
    // 1: 显示的当前温度 右上角是完成，当前有进度条
    // 2: 点击右上角，右上角显示设置 ，进度条消失， 显示的设定温度，弹出弹框
    // 3: 设置温度完成 点击右上角设置。 中间显示的是当前温度，出现进度条
    isEditingStatus (floor) {
      // 0为修改上层， 1为修改下层
      if (!floor) {
        // 编辑状态下菜允许编辑， 选择温湿度后统一发送
        this.isUpSetting = !this.isUpSetting
        if (!this.isUpSetting) {
          let changeTargetArray = ['selectUpFloorTemp', 'selectUpFloorHum']
          // 点击完成的时候只发送改变的值，避免发送未修改的
          if (this.changeNewData.UpTempChange) {
            this.changeData({key: CIGARTYPE.Up_Set_Tempurature, value: this[changeTargetArray[0]]})
            // 每次发送成功后重置，是否改变的状态值，避免一次修改完发送后，每次都是已经改变的状态，导致能够一直发送
            this.changeNewData.UpTempChange = false
          }
          if (this.changeNewData.UpHumChange) {
            this.changeData({key: CIGARTYPE.Up_Set_Humidity, value: this[changeTargetArray[1]]})
            this.changeNewData.UpHumChange = false
          }
          this.waitingTip()
        }
      } else {
        this.isDownSetting = !this.isDownSetting
        if (!this.isDownSetting) {
          let changeTargetArray = ['selectDownFloorTemp', 'selectDownFloorHum']
          if (this.changeNewData.DownTempChange) {
            this.changeData({key: CIGARTYPE.Down_Set_Tempurature, value: this[changeTargetArray[0]]})
            this.changeNewData.DownTempChange = false
          }
          if (this.changeNewData.DownHumChange) {
            this.changeData({key: CIGARTYPE.Down_Set_Humidity, value: this[changeTargetArray[1]]})
            this.changeNewData.DownHumChange = false
          }
          this.waitingTip()
        }
      }
    },

    // 进度条计算方式
    processComputed (current, min, max, floor) {
      let floorOption = floor ? this.isDownSetting : this.isUpSetting
      if (floorOption || current < min) return 0
      if (current > max) return 100
      return (current - min) * 100 / (max - min) || 0
    },

    // 切换开关
    currentOnoff (newValue, mode, isLamplight, is2) {
      if (this.switchSetting) return
      this.switchSetting = true
      window.clearTimeout(this.tid)
      this.tid = window.setTimeout(() => {
        this.switchSetting = false
        let oldValue = mode.value
        let key = mode.key
        if (!isLamplight) {
          newValue = Number(newValue)
        } else {
          if (!newValue) {
            if (oldValue === 1) {
              newValue = is2 ? 0 : 1
            } else if (oldValue === 2) {
              newValue = is2 ? 2 : 0
            } else {
              return
            }
          } else {
            newValue = (is2 ? 1 : 2)
          }
        }
        if (oldValue === newValue) return
        mode.value = newValue
        this.changeData({key, value: newValue})
        this.waitingTip()
      }, 10)
    },
    // 开启倒计时
    // TODO 解构或者重构（优先级低）
    barRemainingTime (mode) {
      let countDownTypes = _.groupBy(this.countDown, (item) => {
        return item.title
      })
      let {title, value} = mode
      // 倒计时为零的时候不显示倒计时
      if (title === 'Lamplight_Switch' && value === 2) {
        if (title === 'Lamplight_Switch' && countDownTypes.Lamplight_Count[0].value !== 0) {
          return `剩余${countDownTypes.Lamplight_Count[0].value}分钟`
        }
      }
      if (title !== 'Lamplight_Switch' && value === 1) {
        if (title === 'Net_Flavor_Degerming' && countDownTypes.Net_Flavor_Degerming_time[0].value !== 0) {
          return `剩余${countDownTypes.Net_Flavor_Degerming_time[0].value}分钟`
        } else if (title === 'Wake_Cigar_Mode' && countDownTypes.Wake_Cigar_Countdown[0].value !== 0) {
          return `剩余${countDownTypes.Wake_Cigar_Countdown[0].value}分钟`
        }
      }
    },
    // 添加设备 扫码
    addDevice () {
      wx.scanQRCode()
    },

    fetchWidth () {
      window.clearTimeout(this.fetchWidthId)
      this.fetchWidthId = setTimeout(() => {
        this.width = window.lib.flexible.rem2px(3.278)
      }, 500)
    },
    fetchHeight () {
      window.clearTimeout(this.fetchHeightId)
      this.fetchHeightId = setTimeout(() => {
        this.height = window.lib.flexible.rem2px(3.278)
      }, 500)
    },
    // 跳转路由到曲线图
    goUrlCurve () {
      let productId = this.currentDevice.pid
      let deviceId = this.currentDevice.id
      this.$router.push({path: `/cigarcurve/${productId}/${deviceId}`})
    },
    // 横竖屏切换重绘
    resize () {
      window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', () => {
        if ([-90, 0, 90, 180].indexOf(window.orientation) !== -1) {
          this.fetchWidth()
          this.fetchHeight()
        }
      })
    },

    // 刷新
    refresh () {
      window.location.reload()
    },
    // 等待状态
    waitingTip () {
      this.$vux.toast.show({
        text: '等待中'
      })
    },
    // 成功状态
    successTip () {
      this.$vux.toast.show({
        text: '修改成功',
        time: 500
      })
    }
  }
}
</script>
<style lang="less">
@import '~vux/src/styles/1px.less';
@import './ios-select.less';
  .cigar--device-control {
    height: 100%;
    font-size: 14px;
    color: #fff;
    background-color: #fff;
    .header {
      height: 1.067rem;
      font-size: 0.373rem;
      line-height: 1.067rem;
      position: relative;
      background: linear-gradient(90deg, #9a753e, #7f5730);
      background: webkit-linear-gradient(90deg, #9a753e, #7f5730);
      .down__arrow {
        position: absolute;
        width: 0.373rem;
        height: 0.373rem;
        top: 0.423rem;
        right: 0.8rem;
        background: url('../../assets/cigrImage/transpate_arrow_down.png');
        background-size:  0.373rem 0.373rem;
      }
      .deviceList-warp {
        z-index: 9999;
        position: absolute; 
        top: 1.067rem;
        right: 15px;            
        width: 255px;
        border-radius: 5px;        
        overflow: hidden;
        .deviceList {
          font-size: 14px;
          width: 100%;
          padding-left: 6px;
          box-sizing: border-box;
          max-height: 290px;
          background-color: #2f262b;
          overflow: auto;
          -webkit-overflow-scrolling: touch;
          .inner-wrap {
            width: 243px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            .deviceList--per {
              position: relative;
              width: 203px;
              text-overflow: ellipsis;
              white-space: nowrap;
              height: 44px;
              line-height: 44px;
              text-indent: 12px;
              .selectImg {
                position: absolute;
                right: -34px;
                top: 16px;
                width: 14px;
                height: 14px;
                background-image: url("../../assets/image/selectImg.png");
                background-size: 14px 14px; 
              }
            }
          }
        }
      }
      .deviceList-warp__icon-angle {
        &::before {
          position: absolute;
          content: "";
          height: 100%;
          box-sizing: border-box;
          padding-bottom: 32px;
          top: 0;
          width: 0;
          right: 30px;
          margin-left: -8px;
          border-left: 8px solid transparent;
          border-right: 8px solid transparent;
          border-bottom: 8px solid #2f262b;
          z-index: 99999;
        }
      }
      .current-device--label {
        float: left
      }
      .current-device--name {
        text-align:center;
        width:100%;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        display: inline-block;
      }
      .weui-cell__bd {
        line-height: 5.9vh;
        &::after {
          border-width: 0 2px 2px 0;
          right: 9%;
          margin-top: -6px;
        }
        .weui-select {
          color: #fff !important;
          height: 6.63vh;
          line-height: 6.63vh;
        }
      }
    }
    .detail {
      background: linear-gradient(135deg, #ac8245, #7c4f2e);
      .top-floor__detail, .bottom-floor__detail{
        padding: 15px 15px 0 15px;
        height: 4.16rem;
        box-sizing: border-box;
        border-top: 1px solid rgba(255, 255, 255, .15);
        border-bottom: 1px solid rgba(255, 255, 255, .15);
        .circle {
          position: relative;
          &__select {
            color: transparent;
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: transparent;
            z-index: 999;
            .weui-cell__bd {
              position: absolute;
              width: 100%;
              height: 100%;
              .weui-select {
                color: transparent;
                position: absolute;
                width: 100%;
                height: 100%;
              }
              &::after {
                border: 0px;
              }
            }
           
          }
        }
        .top-tip {
          height: 0.48rem;
        }
        .top-detail {
          height: calc(100% - 0.48rem);
          position: relative;
          .right, .left {
            width: 50%;
            height: 100%;
            position: absolute;
            top: 0px;
            &.left--position {
              left: 0px;
            }
            &.right--position {
              right: 0px
            }
            .circle {
              width: 3.2rem;
              height: 3.2rem;
              position: absolute;
              left: 50%;
              transform: translateX(-50%);
              .current-temp__wrap, .current-humidity__wrap {
                position: absolute;
                text-align: center;
                width: 3.2rem;
                left: 50%;
                top: 50%;
                -webkit-transform: translateX(-50%);
                transform: translate(-50%, -50%);
                .current-temp--value, .current-humidity--value {
                  font-size: 1.2rem;
                  line-height: 1.2rem;
                }
                .current-temp--unit, .current-humidity--unit {
                  font-size: 0.48rem
                }
                .current-temp--title, .current-humidity--title {
                  color: rgba(255, 255, 255, 0.6)
                }
              }
              .range__temp, .range__humidity {
                width: 136%;
                left: -17%;
                bottom: 0.2rem;
                position: absolute;
              }
              .edit__icon, {
                width: 0.8rem;
                height: 0.8rem;
                position: absolute;
                right: 4px;
                top: 2px;
                z-index: 2;
                overflow: hidden;
                background: url('../../assets/cigrImage/cigar_icon_edit.png');
                background-size: 0.8rem 0.8rem;
                >div {
                  width: 0.8rem;
                  height: 0.8rem;
                  padding-right: 200%;
                  overflow: hidden;
                  box-sizing: border-box
                }
              }
            }
          }
        }
      }
      .top-floor__info, .bottom-floor__info{
        height: 1.33rem;
        .temp {
          height: 1.33rem;
          line-height: 1.33rem;
          .floor {
            margin: 0px 0.667rem 0 0.4rem;
          }
          >div {
            display: inline-block;
          }
        }
        .humidity {
          height: 1.33rem;
          line-height: 1.33rem;
          >div {
            display: inline-block;
            &.down__arrow {
              width: 0.373rem;
              height: 0.373rem;
              margin: 0 0.4rem 0 1.013rem;
              // margin: 0 0.4rem 0 .3rem;
              background: url('../../assets/cigrImage/transpate_arrow_down.png');
              background-size:  0.373rem 0.373rem;
            }
          }
        }
      }
    }
    .switch {
      color: #000;
      font-size: 17px;
      background-color: #e6e6e6; 
      .weui-switch:checked {
        border-color: #d0913d !important;
        background-color: #d0913d !important;
      }
      div {
        .weui-cells {    
          flex: 1;
          display: flex;
          flex-direction: column;
          font-size: 2.54vmax; 
          margin-top: 0px;
        }
        .vux-flexbox {
          padding: 11px 2.1vmax;
          height: 52.8px;
          .normalSwitch {
            margin-left: 2.1vmax !important;
            padding-right: 2.5vmax;
            z-index:1  !important;
          }
          .Lamplight {
            padding-right: 2.5vmax;
            margin-left: -45vw  !important;
            color: transparent  !important;
          }
          .normal {
            position: absolute;
            top: 76%;
            right: 35%;
            font-size: 1.65vmax;
          }
          .light {
            position: absolute;
            top: 76%;
            right: 14%;
            font-size: 1.65vmax;
          }
          .secondary__img--size {
            display: inline-block;
            width: 7.1vmax;
            height: 7.1vmax;
          }
          .Naked_Support_Mode {
            background: url('../../assets/cigrImage/Naked_Support_Mode.png');
            background-size: 7.1vmax 7.1vmax;
          }
          .Wake_Cigar_Mode {
            background: url('../../assets/cigrImage/Wake_Cigar_Mode.png');
            background-size: 7.1vmax 7.1vmax;
          }
          .Net_Flavor_Degerming {
            background: url('../../assets/cigrImage/Net_Flavor_Degerming.png');
            background-size: 7.1vmax 7.1vmax;
          }
          .Lamplight_Switch {
            background: url('../../assets/cigrImage/Lamplight_Switch.png');
            background-size: 7.1vmax 7.1vmax;
          }
          .vux-label-desc {
            font-size: 2.1vmax;
            color: #D0913D;
          }
        }
        .pd8 {
          padding: 8px 2.1vmax;
        }
      }
      .temp-humidity__curve,  {
        margin-top: 10px;
        .temp-humidity__icon {
          width: 7.1vmax;
          height: 7.1vmax;
          padding-right: 15px;
        }
      }
    }
    
    @media all and (orientation : portrait){
      .switch {
        display: flex;
        flex-direction: column;
        flex: 1;
        margin-top: 0;
        div {
          .vux-flexbox {
            .normal-light-status-right {
              right: 35%
            }
            .always-light-status-right {
              right: 14%
            }
          }
        }
      }
      .changeScreen {
        display: flex; 
        flex-direction: column;
      }
      .onlineHight {
        height: 100%;
      }
    }
    @media all and (orientation : landscape){
      .orientToggle {
        .vux-no-group-title {
          .vux-cell-primary {
            padding-left: 3.15%;
          }
        }
      }
      .switch {
        div {
          .vux-flexbox {
            .normal-light-status-right {
              right: 30%
            }
            .always-light-status-right {
              right: 8.5%
            }
          }
        }
      }
      .changeScreen {
        display: block;
      }
    }
  }
  .null-data {
    .bg-img-setting {
      padding-top: 15vh;
      text-align: center;
    }
    .null-device {
      font-size: 16px;
    }
    .bg-img-detail {
      width: 38vh;
      border: 0;
      font-size: 0px;
    }
    .addDevice {
      width: 100%;
      padding: 20px 0 20px 0;
      text-align: center;
    }
    .addDevice {
      .add-font-color {
        width: 30vh;
        color: #d0913d;
        background-color: #fff;
        border: 1px solid #d0913d;
      }
      .weui-btn {
        padding-left: 10vh;
        padding-right: 10vh;
      }
      .weui-btn:after {
        border: none
      }
      button.weui-btn {
        width: auto;
      }
    }
  }
  .currentDeviceOffline {
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
    background: white;
    .bg-img-setting {
      // padding-top: 15vmin;
      margin-top: -18vmin;
      text-align: center;
    }
    .null-device {
      font-size: 16px;
    }
    .bg-img-detail {
      width: 50vmin;
      border: 0;
      font-size: 0px;
    }
    .addDevice {
      width: 100%;
      padding: 20px 0 0px 0;
      text-align: center;
    }
    .addDevice {
      .add-font-color {
        width: 30vh;
        color: #d0913d;
        background-color: #fff;
        border: 1px solid #d0913d;
      }
      .weui-btn {
        padding-left: 24vmin;
        padding-right: 24vmin;
        line-height: 2;
      }
      .weui-btn:after {
        border: none
      }
      button.weui-btn {
        width: auto;
      }
    }
  }
  .mb10 {
    font-size: 10px;
    text-align: center;
    color: black;
  }
</style>
